package com.sxf.mybatis.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.sxf.mybatis.help.ExRowBounds;
import com.sxf.mybatis.help.QueryArrayList;

/**
 * 返回数据结果集处理(如果支持分页,数据统计)
 * 
 * @author SXF
 * 
 */
@Intercepts({ @Signature(type = Executor.class, method = "query", args = {
		MappedStatement.class, Object.class, RowBounds.class,
		ResultHandler.class }) })
public class ProcessExecutorHandlerInterceptor implements Interceptor {

	@SuppressWarnings("unchecked")
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		// Executor executor = (Executor) invocation.getTarget();
		Object obj = invocation.proceed();
		do {
			Object[] paramters = invocation.getArgs();
			RowBounds rowBounds = (RowBounds) paramters[2];
			if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
				break;
			}
			if (rowBounds instanceof ExRowBounds) {
				ExRowBounds bounds = (ExRowBounds) rowBounds;
				List<Object> objList = new ArrayList<Object>();
				if (obj instanceof List) {
					objList = (List<Object>) obj;
				} else {
					objList.add(obj);
				}
				obj = new QueryArrayList<Object>(objList, bounds.getCount());
			}
		} while (false);
		return obj;
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub

	}

}
